﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

using EDTS.Model.Orgnizations;
using EDTS.Data.Orgnizations;
using EDTS.Weixin;
namespace EDTS.Logic.Orgnizations
{
    public class UnitLogic
    {
        /// <summary>
        /// 取得一个单位
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static UnitModel GetModel(Guid guid, bool getapp = false)
        {
            return UnitCommand.GetModel(guid, getapp);
        }
        /// <summary>
        /// 新增一个单位
        /// </summary>
        /// <param name="model"></param>
        public static void CreateNew(UnitModel model)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                UnitCommand.CreateNew(model);

                var token = EDTS.Logic.Weixin.WxAppLogic.GetAccessToken(model.WxAppID.Value);
                var pid = EDTS.Weixin.Submits.Department.Create(token, model.Descript, 1);

                UnitCommand.AddWxDepID(model.Guid, pid);

                ts.Complete();
            }
        }
        /// <summary>
        /// 删除一个单位
        /// </summary>
        /// <param name="guid"></param>
        public static void Delete(Guid guid)
        {
            var unit = GetModel(guid);
            if (unit != null)
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    UnitCommand.Delete(guid);

                    var token = EDTS.Logic.Weixin.WxAppLogic.GetAccessToken(unit.WxAppID.Value);
                    EDTS.Weixin.Submits.Department.Delete(token, unit.WeixinDepartmentID.Value);

                    ts.Complete();
                }
            }
        }
    }
}
